from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
from fake_useragent import UserAgent
import requests
from bs4 import BeautifulSoup
import re
import qtmodern.styles
import qtmodern.windows
import os
import webbrowser


class Ui_MainWindow(QMainWindow):
    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        self.setupUi(self)

    def setupUi(self, MainWindow):
        horizontaHeader = ['书名', '作者及出品','价格', '电子书价格', '地址','封面']

        layout = QGridLayout()
        MainWindow.setObjectName("当当排名")
        MainWindow.resize(1010, 375)
        self.center()  # 将窗口居中显示
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        main_layout = QHBoxLayout(self.centralwidget)

        # 创建一个表格
        self.listView = QTableWidget(MainWindow)
        self.listView.hide()  # 初始隐藏表格
        # 设置表格的列和行数
        self.listView.setColumnCount(6)  # 列数
        self.listView.setRowCount(100)   # 行数
        self.listView.setHorizontalHeaderLabels(horizontaHeader)

        # 设定每列的宽度
        self.listView.horizontalHeader().resizeSection(0, 180)  # 书名
        self.listView.horizontalHeader().resizeSection(1, 180)  # 作者与出版社
        self.listView.horizontalHeader().resizeSection(2, 180)  # 价格
        self.listView.horizontalHeader().resizeSection(3, 180)  # 电子书价格
        self.listView.horizontalHeader().resizeSection(4, 250)  # 地址
        self.listView.horizontalHeader().resizeSection(5, 250)  # 图片
        #self.listView.resizeRowsToContents()
        # 禁止编辑
        self.listView.setEditTriggers(QTableWidget.NoEditTriggers)
        self.listView.setSelectionBehavior(QTableWidget.SelectItems)
        # 绑定双击事件
        self.listView.itemDoubleClicked.connect(self.open_link)

        # 让表格的列自动调整大小
        #self.listView.resizeColumnsToContents()

        # 设置无边框样式
        #self.listView.setFrameShape(QFrame.NoFrame)
        #self.listView.setStyleSheet("QTableWidget { border: none; background-color: transparent; }")

        # 将 QTableWidget 添加到 QScrollArea 中
        scroll_area = QScrollArea()
        scroll_area.setWidget(self.listView)
        scroll_area.setWidgetResizable(True)

        main_layout.addWidget(scroll_area, 1)

        right_layout = QVBoxLayout()
        # 创建查询按钮
        self.inquire = QPushButton(self.centralwidget)
        self.inquire.setObjectName("inquire")
        self.inquire.clicked.connect(self.addNum)
        right_layout.addWidget(self.inquire)
        main_layout.addLayout(right_layout)

        MainWindow.setCentralWidget(self.centralwidget)

        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("dangdang")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)

        QMetaObject.connectSlotsByName(MainWindow)

        #   选择电子还在纸质书
        # 创建
        self.e_dangdang = QComboBox(self)
        # 添加选项
        self.e_dangdang.addItem("纸质书", "dangdang")
        self.e_dangdang.addItem("电子书", "e_dangdang")
        # 设置默认选项（通过索引）
        self.e_dangdang.setCurrentIndex(0)  # 默认选择 "新书热卖榜"
        right_layout.addWidget(self.e_dangdang)
        main_layout.addLayout(right_layout)
        #   选择框排行版
        # 创建
        self.comboBox = QComboBox(self)
        # 添加选项
        self.comboBox.addItem("新书热卖榜","newhotsales")
        self.comboBox.addItem("图书畅销榜","bestsellers")
        self.comboBox.addItem("飙升榜","soaringsales")
        self.comboBox.addItem("特价版","surplusbooks")

        # 设置默认选项（通过索引）
        self.comboBox.setCurrentIndex(0)  # 默认选择 "新书热卖榜"
        right_layout.addWidget(self.comboBox)
        main_layout.addLayout(right_layout)

        #   天数
        # 创建
        self.day = QComboBox(self)
        # 添加选项
        self.day.addItem("24小时", "24hours")
        self.day.addItem("7天", "recent7")
        self.day.addItem("30天", "recent30")
        # 设置默认选项（通过索引）
        self.day.setCurrentIndex(2)  # 默认选择 "30天"
        right_layout.addWidget(self.day)
        main_layout.addLayout(right_layout)

        #   书籍分类
        # 创建
        self.class_data = QComboBox(self)
        # 添加选项
        self.class_data.addItem("全部分类", "01.00.00.00.00.00")
        self.class_data.addItem("计算机/网络", "01.54.00.00.00.00")
        self.class_data.addItem("童书", "01.41.00.00.00.00")
        self.class_data.addItem("中小学用书", "01.43.00.00.00.00")
        self.class_data.addItem("法律", "01.26.00.00.00.00")
        self.class_data.addItem("网络法律法规", "01.26.15.00.00.00")
        # 设置默认选项（通过索引）
        self.class_data.setCurrentIndex(0)  # 默认选择 "全部分类"
        right_layout.addWidget(self.class_data)
        main_layout.addLayout(right_layout)

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "当当排名"))
        self.inquire.setText(_translate("MainWindow", "查询"))

    #   居中
    def center(self):
        qr = self.frameGeometry()  # 获取窗口大小
        cp = QDesktopWidget().availableGeometry().center()  # 获取屏幕中心点
        qr.moveCenter(cp)  # 将窗口矩形的中心设置为屏幕中心
        self.move(qr.topLeft())  # 移动窗口到屏幕中心

    def addNum(self):
        n = 0 # 行数
        #   纸质图书
        if self.e_dangdang.currentData() == "dangdang":
            for i in range(5):
                if self.comboBox.currentData() == "飙升榜":
                    url = "http://bang.dangdang.com/books/soaringsales/01.00.00.00.00.00-0-0-0-1-1"
                else:
                    url = f'http://bang.dangdang.com/books/{self.comboBox.currentData()}/{self.class_data.currentData()}-{self.day.currentData()}-0-0-1-{i}'
                headers = {
                    "user-agent": User_Agent.random
                }
                html = requests.get(url, headers=headers).text
                html_url = BeautifulSoup(html, 'html.parser')
                book = html_url.find(class_='bang_list clearfix bang_list_mode')
                for f in book.find_all('li'):
                    pic = re.findall('http:.*.?html', str(f.find_all(class_="pic")))  # 书籍链接
                    img_url = f.find(class_="pic").find('img')['src']  # 书籍图片
                    self.load_image_from_url(img_url, n,headers)
                    name = re.sub('\（.*', '', f.find(class_='name').text)  # 书籍名称
                    publisher_info = f.find(class_='publisher_info').text  # 作者出版社信息
                    price = re.sub('\n|加入购物车|购买电子书|收藏|\r', '', f.find(class_='price').text)  # 价格
                    price_yj = re.sub('电子书：.*', '', price)  # 非电子价格
                    price_dz = re.findall('电子书：.*', price)  # 电子书
                    self.listView.setItem(n, 0, QTableWidgetItem(name))
                    self.listView.setItem(n, 1, QTableWidgetItem(publisher_info))
                    self.listView.setItem(n, 2, QTableWidgetItem(price_yj))
                    try:
                        self.listView.setItem(n, 3, QTableWidgetItem(price_dz[0]))
                    except IndexError:
                        pass
                    self.listView.setItem(n, 4, QTableWidgetItem(pic[0]))
                    n += 1
        #   电子图书
        elif self.e_dangdang.currentData() == "e_dangdang":
            horizontaHeader = ['书名', '作者及出品', '分类', '电子书价格', '书籍介绍', '封面']
            self.listView.setHorizontalHeaderLabels(horizontaHeader)
            dict_timeDimension = {
                "24hours": "1",
                "recent7": "2",
                "recent30": "3"
            }
            dict_comboBox = {
                "bestsellers": "1",
                "newhotsales": "2",
                "soaringsales": "3"
            }
            start = 0  # 开始
            end = 39  # 结束
            for i in range(5):
                #   判断是否是特价版 如果现在是特价版就跳出循环
                if self.comboBox.currentData() == "surplusbooks":
                    url = "http://e.dangdang.com/media/api.go?action=column&promotionType=1&columnType=all_pcfreebook&isFull=1&returnType=json&deviceSerialNo=html5&macAddr=html5&channelType=html5&permanentId=20241204122115575472956407857123114&returnType=json&channelId=70000&clientVersionNo=6.8.0&platformSource=DDDS-P&fromPlatform=106&deviceType=pconline&token=&start={}&end={}&".format(start,end)
                else:
                    url = "http://e.dangdang.com/media/api.go?action=mediaCategoryLeafNew&promotionType=1&rankType={}&listType=ddds_fastrise&channelType=all&permanentId=20151109120332208112113523718686951&returnType=json&channelId=70000&clientVersionNo=5.0.0&deviceType=DDDS_ALL&category=DZS&payType=1&timeDimension={}&start={}&end={}".format(
                        dict_comboBox[self.comboBox.currentData()],dict_timeDimension[self.day.currentData()],start, end)
                response = requests.get(url)
                dict_book = response.json()['data']['saleList']
                for i in dict_book:
                    headers = {
                        "user-agent": User_Agent.random
                    }
                    book = i["mediaList"][0]
                    authorPenname = book['authorPenname']  # 作者
                    categorys = book['categorys']  # 分类
                    coverPic = book['coverPic']  # 封面
                    if self.comboBox.currentData() == "surplusbooks":
                        promotionPrice = "免费"
                    else:
                        promotionPrice = book['promotionPrice']  # 价格
                    title = book['title']  # 书名
                    descs = book['descs']   # 简介
                    self.listView.setItem(n, 0, QTableWidgetItem(title))
                    self.listView.setItem(n, 2, QTableWidgetItem(categorys))
                    self.listView.setItem(n, 1, QTableWidgetItem(authorPenname))
                    self.listView.setItem(n, 3, QTableWidgetItem(str(promotionPrice)))
                    self.listView.setItem(n, 4, QTableWidgetItem(descs))
                    self.load_image_from_url(coverPic, n, headers)
                    n += 1
                start += 20
                end += 20

    def load_image_from_url(self, image_url, row, headers, width=200, height=150):
        """
        从 URL 加载图片并将其插入到 QTableWidget 中的指定单元格，支持调整图片尺寸
        :param image_url: 图片 URL
        :param row: 行号
        :param headers: 请求头
        :param width: 图片宽度（默认200）
        :param height: 图片高度（默认200）
        """
        import requests
        response = requests.get(image_url, headers=headers)
        if response.status_code == 200:
            # 将响应的内容转换为 QPixmap
            image_data = response.content
            pixmap = QPixmap()
            pixmap.loadFromData(image_data)

            # 调整图片尺寸
            scaled_pixmap = pixmap.scaled(width, height, Qt.KeepAspectRatio, Qt.SmoothTransformation)

            # 创建 QLabel 并设置调整后的图片
            label = QLabel()
            label.setPixmap(scaled_pixmap)
            label.setAlignment(Qt.AlignCenter)  # 设置图片居中显示

            # 将 QLabel 插入到 QTableWidget 中的单元格
            self.listView.setCellWidget(row, 5, label)
            self.listView.setRowHeight(row, 200)  # 设置行高为调整后图片的高度

    def open_link(self, item):
        """双击表格单元格打开链接"""
        row = item.row()
        link = self.listView.item(row, 4).text()  # 获取第5列（地址）的内容
        if link:  # 如果链接存在
            webbrowser.open(link)  # 使用默认浏览器打开链接

    #   错误提示窗口
    def show_message(self, rl="错误"):
        """
        错误提示
        :param rl:
        :return:
        """
        QMessageBox.critical(self, "错误", rl)

if __name__ == '__main__':
    # 获取当前文件所在目录
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    location = os.path.join(BASE_DIR, 'fake_useragent_0.1.11.json')
    User_Agent = UserAgent(verify_ssl=False, use_cache_server=False, path=location)
    # User_Agent = UserAgent()
    app = QApplication(sys.argv)
    qtmodern.styles.light(app)
    window = qtmodern.windows.ModernWindow(Ui_MainWindow())
    window.show()
    sys.exit(app.exec())
